#include "/home/cdd/day5/func.h"
typedef struct shareResource_s {
    int flag; //flag = 0 A没做完 flag = 1 A已经做完了
    pthread_mutex_t mutex;
    pthread_cond_t cond1;//多共享一个条件变量
    pthread_cond_t cond2;
} shareResource_t;
// 线程t1的函数
void* thread1(void* arg) {
    shareResource_t * pshareRes = (shareResource_t *)arg;
    for (int i = 0; i < 3; ++i) {
        pthread_mutex_lock(&pshareRes->mutex);
        while (pshareRes->flag!= 1) {
            pthread_cond_wait(&pshareRes->cond1, &pshareRes->mutex);
        }
        printf("A\n");
        pshareRes->flag= 2;
        pthread_cond_signal(&pshareRes->cond2);
        pthread_mutex_unlock(&pshareRes->mutex);
        pthread_mutex_lock(&pshareRes->mutex);
        while (pshareRes->flag!= 3) {
            pthread_cond_wait(&pshareRes->cond1, &pshareRes->mutex);
        }
        printf("C\n");
        pshareRes->flag= 1;
        pthread_cond_signal(&pshareRes->cond2);
        pthread_mutex_unlock(&pshareRes->mutex);
    }
    return NULL;
}

// 线程t2的函数
void* thread2(void* arg) {
    shareResource_t * pshareRes = (shareResource_t *)arg;
    for (int i = 0; i < 3; ++i) {
        pthread_mutex_lock(&pshareRes->mutex);
        while (pshareRes->flag!= 2) {
            pthread_cond_wait(&pshareRes->cond2, &pshareRes->mutex);
        }
        printf("B\n");
        pshareRes->flag= 3;
        pthread_cond_signal(&pshareRes->cond1);
        pthread_mutex_unlock(&pshareRes->mutex);
    }
    return NULL;
}

int main() {
    shareResource_t shareRes;
    shareRes.flag = 1;
    pthread_mutex_init(&shareRes.mutex,NULL);//创建共享资源并初始化
    pthread_cond_init(&shareRes.cond1,NULL);//初始化好了条件变量
    pthread_cond_init(&shareRes.cond2,NULL);
    pthread_t t1, t2;
    // 创建线程t1
    if (pthread_create(&t1, NULL, thread1, &shareRes)!= 0) {
        perror("pthread_create t1");
        return 1;
    }
    // 创建线程t2
    if (pthread_create(&t2, NULL, thread2, &shareRes)!= 0) {
        perror("pthread_create t2");
        return 1;
    }
    // 等待线程t1和t2结束
    if (pthread_join(t1, NULL)!= 0) {
        perror("pthread_join t1");
        return 2;
    }
    if (pthread_join(t2, NULL)!= 0) {
        perror("pthread_join t2");
        return 2;
    }
    // 销毁互斥锁和条件变量
    pthread_mutex_destroy(&shareRes.mutex);
    pthread_cond_destroy(&shareRes.cond1);
    pthread_cond_destroy(&shareRes.cond2);

    return 0;
}
